import { message, Spin, Tag } from 'antd'
import { Actionable } from '@/desktop/components'
import GroupBindTags from '@/desktop/components/GroupBindTags'
import services from '@/services'
import type { GroupTag } from '@/services/contact-types/groups'
import './tags.module.less'

export default function GroupTags(props: { groupId: string }) {
  const { groupId } = props

  const [boundTags, setBoundTags] = useState<GroupTag[] | null>(null)
  const loadBoundTags = useCallback(async () => {
    const res = await services.groups.getBoundTags(groupId)
    if (res.success) setBoundTags(res.data)
    else void message.warning('群标签加载失败')
  }, [groupId])
  useEffect(() => void loadBoundTags(), [loadBoundTags])

  const [binding, setBinding] = useState(false)
  const finishBinding = useCallback(() => {
    void loadBoundTags()
    setBinding(false)
  }, [loadBoundTags])

  if (!boundTags) return <Spin />

  return <div styleName="tags">
    {boundTags.map(tag => <Tag key={tag.id}>{tag.name}</Tag>)}

    <Actionable>
      <div>
        <a onClick={() => setBinding(true)}>设置标签</a>
      </div>
    </Actionable>

    <GroupBindTags
      groupId={binding ? groupId : null}
      boundTags={boundTags}
      onFinish={finishBinding}
    />
  </div>
}
